package app.server.project.core.syndb;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedDeque;

@Data
@Slf4j
public class ColumnCache {

    private static final int MAX = 100;

    private String key;
    private String sql;
    private String tbName;
    private String columnName;
    private String idName;
    private JdbcTemplate jdbcTemplate;
    private ConcurrentLinkedDeque<ColumnModel> deque = new ConcurrentLinkedDeque<>();

    public ColumnCache(String tbName, String columnName, JdbcTemplate jdbcTemplate, String idName) {
        this.tbName = tbName;
        this.columnName = columnName;
        this.idName = idName;
        this.jdbcTemplate = jdbcTemplate;
        this.key = String.format("%s-%s", tbName, columnName);
        this.sql = String.format("insert into %s(%s,%s) values(?,?) on duplicate key update %s=values(%s) ", tbName, idName, columnName, columnName, columnName);
    }

    /**
     * 添加数据到缓存
     *
     * @param id
     * @param colVal
     */
    public void add(Object id, Object colVal) {
        this.deque.addLast(ColumnModel.of(id, colVal));
    }

    /**
     * 开始同步数据库
     */
    public void synDb() {
        int start = MAX;

        List<Object[]> params = new ArrayList<>();
        HashMap map = new HashMap();
        while (start > 0) {
            var columnModel = this.deque.pollFirst();
            if (Objects.isNull(columnModel)) {
                break;
            }
            map.put(columnModel.getId(), columnModel.getColumnVal());
            start--;
        }
        map.forEach((k, v) -> {
            params.add(new Object[]{k, v});
        });
        if (params.isEmpty()) return;
        var num = this.jdbcTemplate.batchUpdate(this.sql, params);
        log.info("=======tbName:{}==col:{}==更新:{}=======数量{}", this.tbName, this.columnName, num, params.size());
    }

}
